<?php 
	
//过滤POST,GET
function dhtmlspecialchars($string) {
    if(is_array($string)) {
        foreach($string as $key => $val) {
            $string[$key] = dhtmlspecialchars($val);
        }
    } else {
        $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1',
                //$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
                str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
    }
    return $string;
}
function connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset,$type,$hatl=TRUE) {

    $link = null;
    include_once(INC."/adodb5/adodb.inc.php");

    if(isset($type) && $type=='mysql') {
        try {
            $link = NewADOConnection($type);
        }catch (exception $e) {
            echo "Connect Failed";
            //adodb_pr($e);
            die();
        }
        $link->debug=$hatl;
        $link->Connect($dbhost,$dbuser,$dbpw, $dbname);
       	$link->Execute("SET character_set_connection='$dbcharset', character_set_results='$dbcharset', character_set_client='binary'");
        $link->Execute("SET sql_mode=''");
    }elseif(isset($type) && $type=='mssql') {

    }
    return $link;
}
//返回格林威治标准时间
function MyDate($format='Y-m-d H:i:s',$timest=0) {
    $addtime = 8 * 3600;
    if(empty($format)) {
        $format = 'Y-m-d H:i:s';
    }
    return gmdate ($format,$timest+$addtime);
}

function daddslashes($string, $force = 0) {
    !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
    if(!MAGIC_QUOTES_GPC || $force) {
        if(is_array($string)) {
            foreach($string as $key => $val) {
                $string[$key] = daddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}
/**
*	检查登陆状态
*   $state : session里设置的状态值
**/
function checklogin($sta){
	if(!$sta){
		header("Location:../admin/index.php");
	}
}
/**
*   分页传递参数
*   参数 :$page:页码;$total:总条数;$pagesize:每页条数;
**/
function pageclss($page,$total,$pagesize){
		$pagearray = Array();
		$pagearray['pagenow'] = $page;
		$pagearray['all']     = ceil($total/$pagesize);
		$pagearray['nowinfo'] = "第".$page."页|共".$pagearray['all']."页";
		return $pagearray;
}
/**
 * @todo 错误信息导航
 * @author machao
 */
function errorPrompt($errorId,$backUrl){
	header("Location:error.php?err_id=$errorId&back_url=$backUrl");exit;	
}
/**
 * @todo 页面跳转
 * @param unknown_type $url
 * @author machao
 */
function redirect($url){
	header("Location:$url");exit;	
}
/**
 * @todo 验证code是不是手机号码
 * @param unknown_type $code
 * @author machao
 */
function isPhoneNum($code){
	return preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/",$code);	
}
/**
 * @tdo 设置前台登陆session
 * @param unknown_type $id
 * @author machao
 */
function setLoginSession($id){
	session_start();
	$_SESSION['id'] = $id;	
}
/**
 * @todo 获取登陆用户的id
 * @author machao
 */
function getUserId(){
	session_start();
	return isset($_SESSION['id'])?$_SESSION['id']:0;	
}
/**
 * @todo 用户退出登陆
 * Enter description here ...
 * @author machao
 */
function loginOut(){
	session_start();
	unset($_SESSION['id']);
}
/**
 * @todo 截取中文字符
 * @param unknown_type $string
 * @param unknown_type $length
 * @param unknown_type $etc
 */
function truncateutf8($string, $length = 80, $etc = '...')
	{		
		if ($length == 0)
		return '';
		$newlength = 0;
		if (strlen($string) > $length) {			
			for ($i=0; $i<$length; $i++) {
				$newlength++;
				$a  = base_convert(ord($string{$i}), 10, 2);
				$a = substr('00000000' . $a, -8);
				if (substr($a, 0, 1) == 0) {
					continue;
				} elseif (substr($a, 0, 3) == 110) {
					$newlength++;
					$i++;
				} elseif (substr($a, 0, 4) == 1110) {
					$newlength += 2;
					$length++;
					$i++;
				} else {
					$newlength--;
				}
			}
			$length = $newlength;
			
			//return substr($string, 0, $length).$etc;
			return substr($string, 0, $length) . ( $length>=strlen($string) ? '' : $etc );
		} else {
			return $string;
		}
	}
 function csubstr($str, $start=0, $length, $charset="utf-8")
       {
               if(function_exists("mb_substr"))
               {               	
                       if(mb_strlen($str, $charset) <= $length) return $str;
                       $slice = mb_substr($str, $start, $length, $charset);
               }
               else
               {
                       $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
                       $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
                       $re['gbk']          = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
                       $re['big5']          = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
                       preg_match_all($re[$charset], $str, $match);
                       if(count($match[0]) <= $length) return $str;
                       $slice = join("",array_slice($match[0], $start, $length));
               }
              // if($suffix) return $slice."…";
               return $slice;
       }
/**
 * @todo 根据$chapterId散列出小说xx章节的存放位置
 * Enter description here ...
 * @param unknown_type $novelId
 */
function getChapterPath($chapterId){
	//$num   = 2140200;
	$path  = ROOT."/data/";
	$path .= (int)($chapterId/1000000)."/";
	$path .= (int)(($chapterId%1000000)/10000)."/";
	$path .= (int)(($chapterId%10000)/100)."/";
	$path .= $chapterId.".txt";
	return $path;
}
/**
 * @todo 递归的创建目录
 * Enter description here ...
 */
function mkdirExt($path){
	echo $path.'<br>';
	if(is_dir($path)){
		return true;
	}else{
		if(!is_dir(dirname($path))){
			mkdirExt(dirname($path));
			mkdir($path,0777);
		}else{
			 mkdir($path,0777);
		}
	}
}
/**
 * @todo 数组排序
 * Enter description here ...
 */
function orderarray($arr,$arr2,$key,$sort){
	if($key == "time"){
		if($arr != "false"){
			foreach ($arr as $k=>$v){
				$creattime[$v['created']] = $k;
			}
			$creattime = $sort == 'asc'?sort($creattime):ksort($creattime);
			if(is_array($creattime)){
				foreach($creattime as $k=>$v){
					$infp[] = $arr[$v];
				}
				foreach($infp as $k=>$v){
					$info[$k] = $v;
					$info[$k]['bbsnum'] = $arr2!="false"?!empty($arr2[$v['id']])?$arr2[$v['id']]:'0':"0";
				}
			}else{
			foreach($arr as $k=>$v){
				$info['0'] = $v;
				$info['0']['bbsnum'] =  $arr2!="false"?!empty($arr2[$v])?$arr2[$v]:'0':"0";
			}
			}
			return $info;
		}else{
			
			return false;
		}
	}
	if($key == "re"){
	if($arr2 != "false"){
			foreach ($arr2 as $k=>$v){
				$numarray[v]=$k;
			}
			$numarray = $sort =="asc"?sort($numarray):ksort($numarray);
			foreach($numarray as $k=>$v){
				$info[$v] = $arr[$v];
				$info[$v]['bbsnum'] = !empty($v)?$v:'0';
			}
			foreach($arr as $k=>$v){
				if(empty($info[$v['id']])){
					$info[$k] = $v;
					$info[$k]['bbsnum'] = '0';
				} 
			}
			return $info;
		}else{
			foreach($arr as $k=>$v){
				$info['0'] = $v;
				$info['0']['bbsnum'] = '0';
			}
			return $info;
		}
	}
}
?>